//
//  PeopleFilterViewController.m
//  jungoo
//
//  Created by Dang Quang Trung on 8/17/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "PeopleFilterViewController.h"
#import "AppDelegate.h"
#import "User.h"
#import "Request.h"


@implementation NSDictionary (Extension)

- (id)newObjectForKey:(id)aKey
{
    id rez = [self objectForKey:aKey];
    
    return ([rez isKindOfClass:[NSNull class]] ? nil : rez);
}
@end

@implementation PeopleFilterViewController

@synthesize tblView;
@synthesize lastIndexPath;
@synthesize filterStr;
@synthesize delegate;

-(void)initNavigationBar 
{
    [self setBackButtonImageActiveName:nil 
                          inactiveName:@"back-button" 
                                target:self 
                                action:@selector(back)];
    [self setRightButtonImageActiveName:nil 
                           inactiveName:@"done-button" 
                                 target:self 
                                 action:@selector(done)];
    
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg.png"]]]; 
}

-(void)back 
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)done 
{
     NSLog(@"Filter = %@",filterStr);
    [[NSNotificationCenter defaultCenter] postNotificationName:JGO_PEOPLE_CHANGED_FILTER
                                                        object:nil
                                                      userInfo:[NSDictionary dictionaryWithObject:filterStr forKey:@"value"]];
    [self.navigationController popViewControllerAnimated:YES];
    if ([delegate respondsToSelector:@selector(setupViewController:didFinishSetupWithInfo:)]) {
        [delegate setupViewController:self didFinishSetupWithInfo:filterStr];
    }
    
}
- (void)loadData
{ 
    
    //filterStr = @"";
    if ([filterStr isEqualToString:@"All"] || [filterStr isEqualToString:@""]) {
        isAllSelected = YES;
    }
    NSDictionary *user_info = [JGoUtility sharedCreateAccount];
    NSLog(@"%@",user_info);
    [dataArr addObject:[user_info newObjectForKey:@"university"]];
    [dataArr addObject:[user_info newObjectForKey:@"course"]];
    [dataArr addObject:[user_info newObjectForKey:@"u_year"]];
    NSArray *mods = [user_info newObjectForKey:@"modules"];
    for (NSString *theMod in mods) {
        [dataArr addObject:theMod];
    }
    
    [self.tblView reloadData];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
-(void)dealloc
{
    [tblView release];
    [super dealloc];
}
#pragma mark - View lifecycle

- (void)viewDidLoad
{    
    [super viewDidLoad];
    
    [self initNavigationBar];
    [self setTitle:@"Filters"];
    dataArr = [[NSMutableArray alloc]init];
    tblView.backgroundColor = [UIColor clearColor];
    tblView.opaque = NO;
    tblView.backgroundView = nil;
    [self loadData];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return ([dataArr count] ?  1 + [dataArr count] : 0);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}


- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    if (indexPath.row == 0) {
        cell.textLabel.text = @"All";
        if (isAllSelected) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            [cell setSelected:YES animated:TRUE];
        }else{
            cell.accessoryType = UITableViewCellAccessoryNone;
            [cell setSelected:NO animated:TRUE];
            
        }
    }
    else {
        cell.textLabel.text = [dataArr objectAtIndex:indexPath.row-1];
        NSRange substringRange = [filterStr rangeOfString:cell.textLabel.text options:NSCaseInsensitiveSearch];
        
        if ( substringRange.length > 0 ) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            [cell setSelected:YES animated:TRUE];
        }else {
            cell.accessoryType = UITableViewCellAccessoryNone;
            [cell setSelected:NO animated:TRUE];
        }

    }
        
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tblView cellForRowAtIndexPath:indexPath];
    if (indexPath.row == 0) {
        filterStr = @"";
        
        if (isAllSelected) {
            isAllSelected = NO;
        }else{
            isAllSelected = YES;
        }
        [self.tblView reloadData];
    }
    else
    {
        if (!isAllSelected) {
            NSString *cellStr = [dataArr objectAtIndex:(indexPath.row -1)];
            NSLog(@"--- %@ ---",cellStr);
            NSLog(@"--- %@ ---",filterStr);
            NSRange substringRange = [filterStr rangeOfString:cellStr options:NSCaseInsensitiveSearch];
            if ( substringRange.length > 0 ) {
                if (substringRange.location == 0) {
                    NSString *newStr;
                    if (substringRange.length == [filterStr length]) {
                        newStr = @"";
                    }else {
                        newStr = [filterStr substringFromIndex:substringRange.length+1];
                    }
                    
                    filterStr = [newStr retain];
                }else {
                    
                    NSString *sb1;
                    NSString *sb2 ;
                    NSString *newStr ;
                    if (substringRange.location+substringRange.length < [filterStr length]) {
                        sb1 = [filterStr substringToIndex:substringRange.location-1];
                        sb2 = [filterStr substringFromIndex:substringRange.location+substringRange.length+1];
                        newStr = [NSString stringWithFormat:@"%@;%@",sb1,sb2];
                    }else {
                        sb1 = [filterStr substringToIndex:substringRange.location-1];
                        newStr = sb1;
                    }
                    
                    
                    filterStr = [newStr retain];
                }
                
                
                cell.accessoryType = UITableViewCellAccessoryNone;
                [cell setSelected:NO animated:TRUE];
            }else {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
                [cell setSelected:YES animated:TRUE];
                if (filterStr == nil || [filterStr isEqualToString:@""]) {
                    filterStr = [cellStr retain];
                }else {
                    NSString *newStr = [NSString stringWithFormat:@"%@;%@",filterStr,cellStr];
                    filterStr = [newStr retain];
                }
                
            }
            NSLog(@"---- filterStr = %@ -----",filterStr);
        }
        
    }
    /*
    NSLog(@"Filter String: %@",filterStr);
    if (self.lastIndexPath==indexPath) return; // nothing to do
    
    // deselect old
    UITableViewCell *old = [self.tblView cellForRowAtIndexPath:self.lastIndexPath];
    old.accessoryType = UITableViewCellAccessoryNone;
    [old setSelected:FALSE animated:TRUE];
    
    // select new
    UITableViewCell *cell = [self.tblView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    [cell setSelected:TRUE animated:TRUE];
    
    // keep track of the last selected cell
    self.lastIndexPath = indexPath;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:JGO_PEOPLE_CHANGED_FILTER 
                                                        object:nil 
                                                      userInfo:[NSDictionary dictionaryWithObject:filterStr forKey:@"value"]];
     */
    //NSString *favorites = [eventData objectForKey:@"cirValue"];
    //NSDictionary *theUser = (NSDictionary *)sender.userInfo;
    
    
}
@end
